//
//  HealthDataView.m
//  分享demo
//
//  Created by pc-chtypd056 on 2018/8/13.
//  Copyright © 2018年 CTL. All rights reserved.
//

#import "HealthDataView.h"
#import <HealthKit/HealthKit.h>

@interface HealthDataView()<UITextFieldDelegate>
{
    HealthTools *_manager;
    UITextField *numberTextField;
    UILabel * numberLabel;
    UIView * _bgVC;
}

@property (nonatomic, strong) HKHealthStore *healthStore;

@end

@implementation HealthDataView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        
        _manager = [HealthTools sharedInstance];
        if ([HKHealthStore isHealthDataAvailable]) {
            NSSet *writeDataTypes = [_manager dataTypeWrite];//获取写权限
            NSSet *readDataTypes = [_manager dataTypeTRead];//获取写权限
            self.healthStore = [[HKHealthStore alloc] init];
            [self.healthStore requestAuthorizationToShareTypes:writeDataTypes readTypes:readDataTypes completion:^(BOOL success, NSError *error) {
                if (!success) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"获取权限成功" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [alert show];
                }
            }];
        }
        [self uiConfigure];
    }
    return self;
}

- (void)uiConfigure {
    _bgVC = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _bgVC.backgroundColor = Color_RGB(0, 186, 111);
    [self addSubview:_bgVC];
    [self setBgView];
    
    numberTextField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenWIDTH/2-50 , 100, 100, 30)];
    [numberTextField setFont:[UIFont systemFontOfSize:15]];
    [numberTextField setBorderStyle:UITextBorderStyleRoundedRect];
    [numberTextField setKeyboardType:UIKeyboardTypeNumberPad];
    [numberTextField setReturnKeyType:UIReturnKeyDone];
    numberTextField.delegate = self;
    numberTextField.placeholder=@"请输入步数";
    [self addSubview:numberTextField];
    
    UIButton *addBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWIDTH/2-50, 160, 100, 30)];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBtn.backgroundColor=[UIColor redColor];
    [addBtn setTitle:@"添加" forState:UIControlStateNormal];
    [addBtn addTarget:self action:@selector(changeTest) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:addBtn];
    
    
    numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, ScreenHEIGH/2+50, ScreenWIDTH/2, 50)];
    numberLabel.textAlignment=NSTextAlignmentCenter;
    numberLabel.font=[UIFont systemFontOfSize:15];
    [self addSubview:numberLabel];
    
    UIButton * getbtn = [UIButton buttonWithType:UIButtonTypeCustom];
    getbtn.frame=CGRectMake(ScreenWIDTH/2-50, numberLabel.frame.origin.y+numberLabel.frame.size.height, 100, 30);
    getbtn.backgroundColor=[UIColor redColor];
    getbtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [getbtn setTitle:@"查询步数" forState:UIControlStateNormal];
    [getbtn addTarget:self action:@selector(getNewNumberClick) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:getbtn];
}

- (void)getNewNumberClick {
    [_manager authorizeHealthKit:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"success");
            
            [self->_manager getHealthStepCount:^(double value, NSError *error) {
                NSLog(@"1count-->%.0f", value);
                NSLog(@"1error-->%@", error.localizedDescription);
                dispatch_async(dispatch_get_main_queue(), ^{
                    self->numberLabel.text=[NSString stringWithFormat:@"%.f步", value];
                });
            }];
        }
        else {
            
        }
    }];
    
}
-(void)changeTest{
    if (numberTextField.text && ![numberTextField.text isEqualToString:@""]) {
        [self recordWeight:[numberTextField.text doubleValue]];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请输入步数" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alert show];
    }
}

#pragma mark -- UITextFieldDelegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    return YES;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [numberTextField resignFirstResponder];
}

-(void)recordWeight:(double)step{
    //  categoryTypeForIdentifier:HKCategoryTypeIdentifierSleepAnalysis
    HKQuantityType *stepType = [HKQuantityType quantityTypeForIdentifier:HKQuantityTypeIdentifierStepCount];
    if ([HKHealthStore isHealthDataAvailable] ) {
        HKQuantity *stepQuantity = [HKQuantity quantityWithUnit:[HKUnit countUnit] doubleValue:step];
        HKQuantitySample *stepSample = [HKQuantitySample quantitySampleWithType:stepType quantity:stepQuantity startDate:[NSDate date] endDate:[NSDate date]];
        __block typeof(self) weakSelf = self;
        [self.healthStore saveObject:stepSample withCompletion:^(BOOL success, NSError *error) {
            if (success) {
                __block typeof(weakSelf) strongSelf = weakSelf;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"步数已加上" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                    [alert show];
                    
                    strongSelf -> numberTextField.text = @"";
                });
                
                NSLog(@"The data has print");
            }else{
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"加步数失败\n%@",error] delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                [alert show];
            }
        }];
    }
}

- (void)setBgView {
    UIBezierPath * bPath = [UIBezierPath bezierPathWithRect:_bgVC.frame];
    UIBezierPath * aPath = [UIBezierPath bezierPath];
    [aPath moveToPoint:CGPointMake(0, ScreenHEIGH/2+80)];
    [aPath addQuadCurveToPoint:CGPointMake(ScreenWIDTH, ScreenHEIGH/2+80) controlPoint:CGPointMake(ScreenWIDTH/2, ScreenHEIGH/2)];
    [aPath addLineToPoint:CGPointMake(ScreenWIDTH, ScreenHEIGH)];
    [aPath addLineToPoint:CGPointMake(0, ScreenHEIGH)];
    [aPath addLineToPoint:CGPointMake(0, ScreenHEIGH/2+80)];
    CAShapeLayer * layer = [[CAShapeLayer alloc] init];
    [bPath appendPath:[aPath bezierPathByReversingPath]];
    layer.path = bPath.CGPath;
    [_bgVC.layer setMask:layer];
    
}

@end
